<template>
  <div class="gb28181-config">
    <a-form :model="formState" layout="vertical" @finish="handleSubmit">
      <!-- 服务器配置列表 -->
      <a-card 
        title="GB28181国标协议配置" 
        :bordered="false"
      >
        <div class="module-switch">
          <a-form-item label="启用协议" style="margin-bottom: 12px;">
            <a-switch
              v-model:checked="formState.enabled"
              checked-children="启用"
              un-checked-children="禁用"
            />
          </a-form-item>
        </div>

        <div class="servers-header">
          <a-space>
            <span>配置列表</span>
            <a-button 
              type="dashed" 
              size="small" 
              @click="addServer"
              :disabled="formState.servers.length >= 2"
            >
              <PlusOutlined /> 添加服务器
            </a-button>
          </a-space>
          <div class="help-text">最多支持2个服务器配置</div>
        </div>

        <div v-for="(server, serverIndex) in formState.servers" :key="serverIndex" class="server-config">
          <div class="server-header">
            <h4>服务器 {{ serverIndex + 1 }}</h4>
            <a-space>
              <a-form-item 
                label="启用" 
                :name="['servers', serverIndex, 'enabled']"
                style="margin-bottom: 0;"
              >
                <a-switch 
                  v-model:checked="server.enabled" 
                  checked-children="启用" 
                  un-checked-children="禁用" 
                />
              </a-form-item>
              <a-button 
                type="text" 
                danger 
                size="small" 
                @click="removeServer(serverIndex)"
                v-if="formState.servers.length > 1"
              >
                <DeleteOutlined /> 删除
              </a-button>
            </a-space>
          </div>

          <!-- 基本配置 -->
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item 
                label="服务器IP" 
                :name="['servers', serverIndex, 'serverIp']"
                :rules="[
                  { required: true, message: '请输入服务器IP' },
                  { validator: validateServerIP }
                ]"
              >
                <a-input 
                  v-model:value="server.serverIp" 
                  placeholder="192.168.1.100" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item 
                label="端口" 
                :name="['servers', serverIndex, 'serverPort']"
                :rules="[{ required: true, message: '请输入端口' }]"
              >
                <a-input-number 
                  v-model:value="server.serverPort" 
                  :min="1" 
                  :max="65535" 
                  placeholder="5060" 
                  style="width: 100%" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item 
                label="服务器ID" 
                :name="['servers', serverIndex, 'serverId']"
                :rules="[
                  { required: true, message: '请输入服务器ID' },
                  { validator: validateServerIdFormat }
                ]"
              >
                <a-input 
                  v-model:value="server.serverId" 
                  placeholder="34020000002000000001" 
                  maxlength="20" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item 
                label="认证密码" 
                :name="['servers', serverIndex, 'password']"
                :rules="[{ required: true, message: '请输入密码' }]"
              >
                <a-input-password 
                  v-model:value="server.password" 
                  placeholder="12345678" 
                />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 详细配置 -->
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item 
                label="设备ID" 
                :name="['servers', serverIndex, 'deviceId']"
                :rules="[
                  { required: true, message: '请输入设备ID' },
                  { validator: validateDeviceIdFormat }
                ]"
              >
                <a-input 
                  v-model:value="server.deviceId" 
                  placeholder="34020000001320000001" 
                  maxlength="20" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item 
                label="本地端口" 
                :name="['servers', serverIndex, 'localPort']"
              >
                <a-input-number 
                  v-model:value="server.localPort" 
                  :min="1" 
                  :max="65535" 
                  placeholder="5060" 
                  style="width: 100%" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item 
                label="行政区划" 
                :name="['servers', serverIndex, 'civilCode']"
                :rules="[
                  { required: true, message: '请输入行政区划' },
                  { validator: validateCivilCodeFormat }
                ]"
              >
                <a-input 
                  v-model:value="server.civilCode" 
                  placeholder="340200" 
                  maxlength="6" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item 
                label="域名" 
                :name="['servers', serverIndex, 'domain']"
                :rules="[
                  { required: true, message: '请输入域名' },
                  { validator: validateDomainFormat }
                ]"
              >
                <a-input 
                  v-model:value="server.domain" 
                  placeholder="3402000000" 
                  maxlength="10" 
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="心跳周期(秒)">
                <a-input-number 
                  v-model:value="server.heartbeatInterval" 
                  :min="10" 
                  :max="300" 
                  placeholder="60" 
                  style="width: 100%" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="注册间隔(秒)">
                <a-input-number 
                  v-model:value="server.registerInterval" 
                  :min="300" 
                  :max="7200" 
                  placeholder="3600" 
                  style="width: 100%" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="注册过期(秒)">
                <a-input-number 
                  v-model:value="server.registerExpires" 
                  :min="300" 
                  :max="7200" 
                  placeholder="3600" 
                  style="width: 100%" 
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="超时次数">
                <a-input-number 
                  v-model:value="server.maxTimeoutCount" 
                  :min="1" 
                  :max="10" 
                  placeholder="3" 
                  style="width: 100%" 
                />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 通道配置 -->
          <a-form-item label="通道配置">
            <div class="channels-config">
              <div class="channels-header">
                <span>通道数量: </span>
                <a-input-number 
                  v-model:value="server.channelCount" 
                  :min="1" 
                  :max="16" 
                  style="width: 80px" 
                />
                <a-button 
                  type="link" 
                  size="small" 
                  @click="generateChannels(serverIndex)"
                >
                  自动生成
                </a-button>
              </div>
              
              <div v-if="server.channels && server.channels.length > 0" class="channels-list">
                <div v-for="(channel, channelIndex) in server.channels" :key="channelIndex" class="channel-item">
                  <a-input-group compact>
                    <a-input 
                      v-model:value="channel.channel_id" 
                      style="width: 50%" 
                      :placeholder="`通道${channelIndex + 1}ID`" 
                    />
                    <a-input 
                      v-model:value="channel.channel_name" 
                      style="width: 50%" 
                      :placeholder="`通道${channelIndex + 1}名称`" 
                    />
                  </a-input-group>
                </div>
              </div>
            </div>
          </a-form-item>
        </div>
      </a-card>

      <!-- 操作按钮 -->
      <div style="margin-top: 24px">
        <a-space>
          <a-button type="primary" html-type="submit" :loading="loading">
            保存配置
          </a-button>
          <a-button @click="handleReset">
            重置
          </a-button>
          <a-button @click="fetchConfig">
            刷新
          </a-button>
        </a-space>
      </div>
    </a-form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { 
  getGB28181Config, 
  setGB28181Config,
  validateDeviceId,
  validateServerId,
  validateCivilCode,
  validateDomain,
  validateChannelId,
  validateIP,
  validatePort
} from '@/api/gb28181';

export default defineComponent({
  name: 'GB28181Config',
  components: {
    PlusOutlined,
    DeleteOutlined
  },
  setup() {
    const createDefaultServer = () => ({
      enabled: true, // 默认启用
      serverIp: '',
      serverPort: 5060,
      localPort: 5060,
      password: '12345678',
      serverId: '',
      deviceId: '',
      civilCode: '',
      domain: '',
      heartbeatInterval: 60,
      registerInterval: 3600,
      registerExpires: 3600,
      maxTimeoutCount: 3,
      channelCount: 2,
      channels: []
    });

    const defaultSettings = () => ({
      enabled: true,
      servers: [createDefaultServer()]
    });

    const formState = reactive(defaultSettings());
    const loading = ref(false);

    // 添加服务器
    const addServer = () => {
      if (formState.servers.length < 2) {
        formState.servers.push(createDefaultServer());
      }
    };

    // 删除服务器
    const removeServer = (index) => {
      if (formState.servers.length > 1) {
        formState.servers.splice(index, 1);
      }
    };

    // 生成通道配置
    const generateChannels = (serverIndex) => {
      const server = formState.servers[serverIndex];
      const channels = [];
      for (let i = 0; i < server.channelCount; i++) {
        channels.push({
          channel_id: generateChannelId(server.deviceId, i + 1),
          channel_name: `摄像头 ${i + 1}`
        });
      }
      server.channels = channels;
    };

    // 生成通道ID
    const generateChannelId = (deviceId, channelNum) => {
      if (deviceId && deviceId.length === 20) {
        const baseId = deviceId.substring(0, 17);
        const channelId = channelNum.toString().padStart(3, '0');
        return baseId + channelId;
      }
      return '';
    };

    // 验证函数
    const validateServerIP = async (rule, value) => {
      if (value && !validateIP(value)) {
        return Promise.reject('请输入有效的IP地址');
      }
      return Promise.resolve();
    };

    const validateServerIdFormat = async (rule, value) => {
      if (value && !validateServerId(value)) {
        return Promise.reject('服务器ID必须为20位数字');
      }
      return Promise.resolve();
    };

    const validateDeviceIdFormat = async (rule, value) => {
      if (value && !validateDeviceId(value)) {
        return Promise.reject('设备ID必须为20位数字');
      }
      return Promise.resolve();
    };

    const validateCivilCodeFormat = async (rule, value) => {
      if (value && !validateCivilCode(value)) {
        return Promise.reject('行政区划代码必须为6位数字');
      }
      return Promise.resolve();
    };

    const validateDomainFormat = async (rule, value) => {
      if (value && !validateDomain(value)) {
        return Promise.reject('域名必须为10位数字');
      }
      return Promise.resolve();
    };

    // 获取配置
    const fetchConfig = async () => {
      try {
        loading.value = true;
        const response = await getGB28181Config();
        
        if (response) {
          formState.enabled = typeof response.enabled === 'boolean' ? response.enabled : true;

          const servers = Array.isArray(response.sip_server) ? response.sip_server : [];
          if (servers.length > 0) {
            formState.servers = servers.map(sipConfig => ({
              enabled: sipConfig.enabled !== undefined ? sipConfig.enabled : true,
              serverIp: sipConfig.server_ip || '',
              serverPort: sipConfig.server_port || 5060,
              localPort: sipConfig.local_port || 5060,
              password: sipConfig.password || '',
              serverId: sipConfig.server_id || '',
              deviceId: sipConfig.device_id || '',
              civilCode: sipConfig.civil_code || '',
              domain: sipConfig.domain || '',
              heartbeatInterval: sipConfig.heartbeat_interval || 60,
              registerInterval: sipConfig.register_interval || 3600,
              registerExpires: sipConfig.register_expires || 3600,
              maxTimeoutCount: sipConfig.max_timeout_count || 3,
              channelCount: sipConfig.channel_count || (sipConfig.channels ? sipConfig.channels.length : 2),
              channels: Array.isArray(sipConfig.channels)
                ? sipConfig.channels.map(channel => {
                    if (typeof channel === 'string') {
                      return { channel_id: channel, channel_name: '' };
                    }
                    return {
                      channel_id: channel?.channel_id || channel?.id || '',
                      channel_name: channel?.channel_name || channel?.name || ''
                    };
                  })
                : []
            }));
          } else {
            formState.servers = [createDefaultServer()];
          }
        }
      } catch (error) {
        console.error('获取GB28181配置失败:', error);
        message.error('获取配置失败，请刷新页面重试');
      } finally {
        loading.value = false;
      }
    };

    // 提交配置
    const handleSubmit = async () => {
      try {
        loading.value = true;

        // 根据协议文档，参数直接是数组
        const config = {
          enabled: formState.enabled,
          sip_server: formState.servers.map(server => ({
            enabled: server.enabled,
            channel_count: server.channelCount,
            civil_code: server.civilCode,
            device_id: server.deviceId,
            channels: Array.isArray(server.channels)
              ? server.channels
                  .map(channel => channel?.channel_id || channel?.id || '')
                  .filter(item => item)
              : [],
            domain: server.domain,
            heartbeat_interval: server.heartbeatInterval,
            local_port: server.localPort,
            max_timeout_count: server.maxTimeoutCount,
            password: server.password,
            register_interval: server.registerInterval,
            register_expires: server.registerExpires,
            server_id: server.serverId,
            server_ip: server.serverIp,
            server_port: server.serverPort
          }))
        };

        const response = await setGB28181Config(config);
        message.success('GB28181配置已保存');
      } catch (error) {
        console.error('保存GB28181配置失败:', error);
        message.error('保存失败: ' + (error.message || '请重试'));
      } finally {
        loading.value = false;
      }
    };

    // 重置配置
    const handleReset = () => {
      const reset = defaultSettings();
      formState.enabled = reset.enabled;
      formState.servers = reset.servers;
      message.info('已重置为默认设置');
    };

    onMounted(() => {
      fetchConfig();
    });

    return {
      formState,
      loading,
      addServer,
      removeServer,
      generateChannels,
      generateChannelId,
      handleSubmit,
      handleReset,
      fetchConfig,
      validateServerIP,
      validateServerIdFormat,
      validateDeviceIdFormat,
      validateCivilCodeFormat,
      validateDomainFormat
    };
  }
});
</script>

<style scoped>
.gb28181-config {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.module-switch {
  margin-bottom: 16px;
}

.help-text {
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.servers-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.server-config {
  padding: 20px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  margin-bottom: 16px;
  background-color: #fafafa;
}

.server-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.server-header h4 {
  margin: 0;
  color: #333;
  font-weight: 500;
}

.channels-config {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 12px;
  background-color: #fff;
}

.channels-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.channels-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.channel-item {
  display: flex;
  align-items: center;
}

:deep(.ant-input-number) {
  width: 100%;
}
</style> 
